package api

import (
	"service"
	"github.com/gin-gonic/gin"
	"pojo/form"
	"pojo/vo"
	"constant"
	"net/http"
	"strconv"
)

type GoodsApi struct {
	service *service.GoodsService
}

// 创建GoodsApi
func NewGoodsApi(service *service.GoodsService) *GoodsApi {

	return &GoodsApi{
		service: service,
	}
}

// 新增商品信息
func (this *GoodsApi) Insert(ctx *gin.Context) {

	goodsInfo := &form.GoodsForm{}
	ctx.Bind(goodsInfo)

	err := this.service.InsertGoods(goodsInfo)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "保存商品失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 根据id更新商品信息
func (this *GoodsApi) Update(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	goodsInfo := &form.GoodsForm{}
	ctx.Bind(goodsInfo)
	goodsInfo.Id = id

	err := this.service.UpdateGoods(goodsInfo)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "保存商品失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 分页查询商品信息
func (this *GoodsApi) List(ctx *gin.Context) {
	query := &form.GoodsPageQueryForm{}
	ctx.Bind(query)
	result := this.service.QueryGoods(query)
	ctx.JSON(http.StatusOK, result)
}

// 删除商品信息
func (this *GoodsApi) Delete(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	err := this.service.DeleteGoods(id)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "删除商品失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 根据ID查询商品信息
func (this *GoodsApi) Find(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	goodsInfo, err := this.service.FindGoods(id)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "查询商品失败"
	} else {
		result = constant.SUCCESS
		result.Info = goodsInfo
	}

	ctx.JSON(http.StatusOK, result)
}

